package com.LeetCode.StackAndHeap;

import org.junit.Test;

import java.util.Stack;

/**
 * 逆波兰表达求求值
 */
public class EvalRPN {



    public int evalRPN(String[] tokens) {

        Stack<Integer> stack = new Stack<>();
        int len = tokens.length;
        for(int i = 0; i<len; i++){
            if(tokens[i].equals("+") || tokens[i].equals("-") || tokens[i].equals( "*" )|| tokens[i].equals("/")){
                int b = stack.peek();
                stack.pop();
                int a = stack.peek();
                stack.pop();
                int curRes = 0;
                if (tokens[i].equals("+")) {
                    curRes = a + b;
                } else if (tokens[i].equals("-")) {
                    curRes = a - b;
                } else if (tokens[i].equals("*")) {
                    curRes = a * b;
                } else if (tokens[i].equals("/")) {
                    curRes = a / b;
                }
                stack.push(curRes);
            }else {
                stack.push(Integer.valueOf(tokens[i]));
            }
        }
        return stack.peek();
    }


    @Test
    public void test(){
        String[] strs = {"10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"};
        System.out.println(evalRPN(strs));
    }
}
